#!/usr/bin/env python3
"""
Start both backend and frontend servers
"""

import subprocess
import sys
import time
import signal
import os
from pathlib import Path

def start_backend():
    """Start the backend server"""
    print("🚀 Starting backend server (demo_server.py)...")
    return subprocess.Popen([
        sys.executable, "demo_server.py"
    ], cwd=Path(__file__).parent)

def start_frontend():
    """Start the frontend server"""
    print("🌐 Starting frontend server...")
    return subprocess.Popen([
        sys.executable, "simple_frontend_server.py"
    ], cwd=Path(__file__).parent)

def main():
    """Main function"""
    print("=" * 70)
    print("🎯 Event Contract Platform - Dual Server Startup")
    print("=" * 70)
    
    backend_process = None
    frontend_process = None
    
    try:
        # Start backend server
        backend_process = start_backend()
        time.sleep(3)  # Wait for backend to start
        
        # Start frontend server
        frontend_process = start_frontend()
        time.sleep(2)  # Wait for frontend to start
        
        print("\n✅ Both servers started successfully!")
        print("=" * 70)
        print("🔗 Frontend: http://localhost:8000")
        print("📡 Backend WebSocket: ws://localhost:8768")
        print("🔍 Backend Health: http://localhost:8768 (if using FastAPI version)")
        print("=" * 70)
        print("\n📖 Usage Instructions:")
        print("1. Open http://localhost:8000 in your browser")
        print("2. Create a user account")
        print("3. Start trading!")
        print("\n⚠️  Note: Make sure you have proxy settings if accessing Binance API")
        print("\n🛑 Press Ctrl+C to stop both servers")
        print("=" * 70)
        
        # Wait for processes
        while True:
            if backend_process.poll() is not None:
                print("❌ Backend server stopped unexpectedly")
                break
            if frontend_process.poll() is not None:
                print("❌ Frontend server stopped unexpectedly")
                break
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n🛑 Stopping servers...")
    
    finally:
        # Clean up processes
        if backend_process:
            try:
                backend_process.terminate()
                backend_process.wait(timeout=5)
                print("✅ Backend server stopped")
            except:
                backend_process.kill()
                print("⚠️  Backend server force killed")
        
        if frontend_process:
            try:
                frontend_process.terminate()
                frontend_process.wait(timeout=5)
                print("✅ Frontend server stopped")
            except:
                frontend_process.kill()
                print("⚠️  Frontend server force killed")
        
        print("👋 Goodbye!")

if __name__ == "__main__":
    main()
